import React, { createRef } from 'react'
import {
  Form,
  Icon,
  Input,
  Card,
  Cascader,
  Upload,
  Modal,
  Button,
  message,
} from 'antd'
import RichEdit from './richEdit'
import LinkA from '@/components/publics/LinkA.jsx'
import {
  addOrUpdate,
  reqCategory,
  findOneById,
  getCategorys,
} from '@/api/product-api.js'
import { upload } from '@/api/upload-api.js'
const { TextArea } = Input

class Editform extends React.Component {
  constructor(props) {
    super(props)
    this.rich = createRef()
    this.state = {
      previewVisible: false,
      previewImage: '',
      fileList: [],
      loading: false,
      form: {},
      categorys: [],
      selectCategoryId: null,
    }
  }
  componentDidMount() {
    findOneById(this.props.match.params.id).then((v) => {
      if (v.status === 0) {
        const imgs = v.data.imgs.map((item) => {
          return {
            uid: parseInt(Math.random() * 100),
            name: 'image.png',
            status: 'done',
            url: item,
          }
        })
        this.setState({
          form: v.data,
          fileList: imgs,
        })
      }
    })
    getCategorys().then((v) => {
      if (v.status === 0) {
        this.setState({
          categorys: v.data,
        })
      }
    })
  }
  uploadImg = (detail) => {
    const self = this
    upload(detail.file).then((v) => {
      if (v.status === 0) {
        self.setState({
          fileList: [
            ...self.state.fileList,
            {
              uid: parseInt(Math.random() * 100),
              name: 'image.png',
              status: 'done',
              url: v.data.url,
            },
          ],
        })
      } else {
        message.error(v.msg || '上传失败')
      }
    })
  }
  formItemLayout = {
    labelCol: { span: 2 },
    wrapperCol: { span: 8 },
  }
  formItemLayoutBtn = {
    wrapperCol: { offset: 2 },
  }

  formItemLayoutRich = {
    labelCol: { span: 2 },
    wrapperCol: { span: 18 },
  }

  getBase64 = (file) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => resolve(reader.result)
      reader.onerror = (error) => reject(error)
    })
  }

  handleCancel = () => this.setState({ previewVisible: false })

  handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj)
    }
    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
    })
  }
  getImgAndRichContent = () => {
    return {
      fileList: this.state.fileList,
      richContent: this.rich.current.getRichContent(),
    }
  }
  selectCas = (e) => {
    this.setState({
      selectCategoryId: e[e.length - 1],
    })
  }
  handleOk = (e) => {
    e.preventDefault()
    this.props.form.validateFields().then((values, err) => {
      const v = this.getImgAndRichContent()
      debugger
      values.imgs = v.fileList.map((v) => v.url)
      values.detail = v.richContent
      values.categoryId = this.state.selectCategoryId
      if (!err) {
        this.setState(
          {
            form: { ...this.state.form, ...values },
          },
          () => {
            addOrUpdate(this.state.form).then((v) => {
              if (v.status === 0) {
                message.success('保存成功')
                this.props.history.replace('/goods/product')
              } else {
                message.error(v.msg || '保存失败')
              }
            })
          }
        )
      }
    })
  }
  render() {
    const { getFieldDecorator } = this.props.form
    const title = (
      <div>
        <LinkA>
          <Icon
            type="arrow-left"
            style={{ color: 'green', fontSize: '18px', marginRight: '10px' }}
          />
        </LinkA>
        <span>商品编辑</span>
      </div>
    )
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">上传图片</div>
      </div>
    )
    return (
      <Card title={title} bordered={false}>
        <Form className="product-edit">
          <Form.Item {...this.formItemLayout} label="商品名称">
            {getFieldDecorator('name', {
              initialValue: this.state.form.name,
              rules: [{ required: true, message: '请填写商品名称' }],
            })(<Input />)}
          </Form.Item>
          <Form.Item {...this.formItemLayout} label="商品描述">
            {getFieldDecorator('desc', {
              initialValue: this.state.form.desc,
              rules: [{ required: true, message: '请填写商品描述' }],
            })(<TextArea placeholder="请填写商品描述" />)}
          </Form.Item>
          <Form.Item {...this.formItemLayout} label="商品价格">
            {getFieldDecorator('price', {
              initialValue: this.state.form.price,
              rules: [{ required: true, message: '请填写商品价格' }],
            })(<Input addonAfter="元" />)}
          </Form.Item>
          <Form.Item {...this.formItemLayout} label="商品分类">
            {getFieldDecorator('categoryId', {
              initialValue: [this.state.form.categoryId],
              rules: [{ required: true, message: '请填写商品分类' }],
            })(
              <Cascader
                options={this.state.categorys}
                onChange={this.selectCas}
                placeholder="请填写商品分类"
              />
            )}
          </Form.Item>
          <Form.Item {...this.formItemLayout} label="商品图片">
            <Upload
              listType="picture-card"
              fileList={this.state.fileList}
              onPreview={this.handlePreview}
              customRequest={this.uploadImg}
            >
              {this.state.fileList.length >= 8 ? null : uploadButton}
            </Upload>
            <Modal
              visible={this.state.previewVisible}
              footer={null}
              onCancel={this.handleCancel}
            >
              <img
                alt="example"
                style={{ width: '100%' }}
                src={this.state.previewImage}
              />
            </Modal>
          </Form.Item>
          <Form.Item {...this.formItemLayoutRich} label="商品详情">
            <RichEdit ref={this.rich} oldVal={this.state.form.detail} />
          </Form.Item>
          <Form.Item {...this.formItemLayoutBtn}>
            <Button type="primary" onClick={(e) => this.handleOk(e)}>
              提交
            </Button>
          </Form.Item>
        </Form>
      </Card>
    )
  }
}

export default Form.create()(Editform)
